package com.axx.android.subject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.moments.ImageAdapter;
import com.axx.android.moments.ImageModel;
import com.axx.android.moments.LocationChooseActivity;
import com.axx.android.moments.MomentActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageUtils;
import com.axx.android.utils.ViewUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class SubjectWriteActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    Button mBtnBack;
    @Bind(R.id.btn_send)
    Button mBtnSend;
    @Bind(R.id.et_content)
    EditText mEtContent;
    @Bind(R.id.tv_location)
    TextView mTvLocation;
    @Bind(R.id.rv_image)
    RecyclerView mRvImage;
    @Bind(R.id.activity_moment)
    LinearLayout mActivityMoment;

    private List<ImageModel> imageModelList = new ArrayList<>();
    private ImageAdapter imageAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_subject_write;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mTvLocation.setText(LetterApp.curLocation.getAddress());
        ImageModel imageModel = new ImageModel();
        imageModel.setAdd(true);
        imageModelList.add(imageModel);

        imageAdapter = new ImageAdapter(R.layout.view_item_image, imageModelList);
        mRvImage.setAdapter(imageAdapter);
        int w = getResources().getDisplayMetrics().widthPixels;
        int count = w / ViewUtils.dip2px(this, 72);
        mRvImage.setLayoutManager(new GridLayoutManager(this, count));
        imageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ImageModel imageModel1 = imageModelList.get(position);
                if (imageModel1.isAdd()) {
                    MultiImageSelector.create().start(SubjectWriteActivity.this, 200);
                }
            }
        });
        imageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_del) {
                    imageModelList.remove(position);
                    imageAdapter.notifyDataSetChanged();
                } else {
                    ImageModel imageModel1 = imageModelList.get(position);
                    if (imageModel1.isAdd()) {
                        MultiImageSelector.create().start(SubjectWriteActivity.this, 200);
                    }
                }
            }
        });
    }

    @OnClick(R.id.btn_send)
    public void onViewClicked() {
        fetchSend();
    }

    private void fetchSend() {
        showLoading("");
        String subjectId = getIntent().getStringExtra("subjectId");
        HashMap<String, String> map = new HashMap<>();
        map.put("text", mEtContent.getText().toString());
        map.put("subjectId", subjectId);
        map.put("userId", LetterApp.authUser.getId());
        map.put("token", LetterApp.authUser.getToken());
        if (imageModelList.size() != 1) {
            StringBuilder stringBuilder = new StringBuilder();
            for (ImageModel imageModel : imageModelList) {
                if (!TextUtils.isEmpty(imageModel.getImageId())) {
                    stringBuilder.append(imageModel.getImageId()).append("#");
                }

            }

            String pic = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
            map.put("picStr", pic);
        }

        HttpUtils.post(Constants.Url.Subject.SUBJECT_PUSH, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel>() {
                    });
                    if (baseModel.isSuccess()) {
                        showToast(baseModel.message);
                        EventBus.getDefault().post(new RefreshEvent());
                        finish();
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                showToast("发送失败");
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            if (resultCode == RESULT_OK) {
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                String imagePath = path.get(0);
                if (imagePath != null) {
                    showLoading("上传照片中");
                    uploadImage(imagePath);
                } else {
                    showToast("选图失败，请重新选择");
                }

            }
        }
        if (requestCode == 300){
            if (resultCode ==301){
                mTvLocation.setText(data.getStringExtra("address"));
            }
        }
    }

    @OnClick(R.id.tv_location)
    public void chooseLocation() {
        startActivityForResult(new Intent(this, LocationChooseActivity.class),300);
    }

    private void uploadImage(final String imagePath) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId", LetterApp.authUser.getId());

        HttpUtils.postFile(ImageUtils.DEFAULT_IMAGE_SIZE,Constants.Url.Uploader.UPLOAD_IMAGE_V2, "file", new File(imagePath), hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel<String> baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<String>>() {
                    });
                    if (baseModel.isSuccess()) {
                        final ImageModel imageModel = new ImageModel();
                        imageModel.setAdd(false);
                        imageModel.setCanDel(true);
                        imageModel.setUrl(imagePath);
                        imageModel.setImageId(baseModel.data);
                        imageModelList.add(imageModel);
                        imageAdapter.notifyDataSetChanged();
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }
}
